import type { Map, MapMouseEvent } from 'mapbox-gl'
import { meter2MetricStr } from '@/widgets'
import { distance, featureOfCircle, type LngLat } from '@/geom/great-circle'
import { overlay } from '@/map'
import { highLightProperties } from '@/map/highlights'
import { IgnoreMouseDrag, isRight, type InteractionTip } from '@/map-interaction'
import { addAuxCircle } from './core'

export class DrawAuxCircle extends IgnoreMouseDrag {
  public readonly type: string = 'DrawAuxCircle'
  private center: LngLat | null = null
  private centerCoord: number[] = []
  private radius: number = 0
  private properties = highLightProperties.line.primary

  public readonly tip: InteractionTip = {
    title: '绘制辅助圆',
    content: '1. 左键点击绘制辅助圆.\n2. 右键取消绘制.'
  }

  public attach(map: Map): void {
    super.attach(map)
    map.getCanvas().style.cursor = 'crosshair'
  }

  public detach(map: Map): void {
    map.getCanvas().style.cursor = 'auto'
    super.detach(map)
  }

  public onMouseMove(evt: MapMouseEvent): void {
    const { center } = this
    if (!center) {
      return
    }
    const { lng, lat } = evt.lngLat
    const pt = { lng, lat }
    const radius = distance(center, pt)
    this.radius = radius
    const f = featureOfCircle(center, radius, this.properties)
    overlay.updateLine(f)
    const txt = ` \n${meter2MetricStr(radius)}`
    overlay.updateSymbol({
      type: 'Feature',
      geometry: {
        type: 'Point',
        coordinates: this.centerCoord
      },
      properties: highLightProperties.symbol.primary(txt)
    })
  }

  public onMouseClick(evt: MapMouseEvent): void {
    if (isRight(evt)) {
      this.finish()
      return
    }
    const { center, radius } = this
    if (!center) {
      const { lng, lat } = evt.lngLat
      const pt = { lng, lat }
      this.center = pt
      this.centerCoord = [lng, lat]
      return
    }
    addAuxCircle(center, radius)
    this.finish()
    return
  }
}
